console.log("%c YimaoSoft Admin %c v3.0.0 %c","background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;","background:#3488ff; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;","background:transparent;");
console.log("Web http://www.91site.net/");
console.log("%c 开发人员 Yimao %c zjutsxj@qq.com | 425225349 %c","background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;","background:#3488ff; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;","background:transparent;");

/**
 * sxj 函数库
 * @return {[type]} [description]
 */
var sxj = function() {
    /** 隐藏显示加载 **/
    function loading(status = true) {
        // <div class="load-indicator" id="load-indicator"></div>
        var div_loading = $("#load-indicator"); // 显示加载中的div
        // 生成加载div 并且添加到body 
        if (!div_loading[0]) {
            var Ele = $('<div data-loading="loading..." class="load-indicator" id="load-indicator"></div>');
            $('body').append(Ele);
        }
        div_loading = $("#load-indicator"); // 显示加载中的div

        // 显示加载
        if (status) {
            div_loading.addClass('loading');
            div_loading.show();
        }
        // 隐藏加载
        if (!status || status == 'hide') {
            div_loading.removeClass('loading');
            div_loading.hide(1000);
        }
    }

    // 阻止冒泡事件
    function stop_event(event) {
        event.stopImmediatePropagation();
        event.stopPropagation();
    }

    // 删除图片列表中的图片
    function upload_list_delete(url, el) {
        bootbox.confirm({
            message: "确定要删除文件？删除后无法恢复",
            callback: function(result) {
                if (result) {
                    loading();
                    $.ajax({
                        url: url,
                        type: "DELETE",
                        success: function(result) {
                            if (result.code == '1') msg_success(result.msg);
                            if (result.code == '0') msg_error(result.msg);
                            el.remove();
                        },
                        error: function() {
                            msg_error();
                        }
                    });
                }
            }
        });
    }

    // 删除文件 清空input里面的内容
    function upload_delete(url, input_name) {
        bootbox.confirm({
            message: "确认删除？删除后无法恢复。",
            callback: function(result) {
                if (result) {
                    loading();
                    $.ajax({
                        url: url,
                        type: "DELETE",
                        success: function(result) {
                            if (result.code == '1') msg_success(result.msg);
                            if (result.code == '0') msg_error(result.msg);
                            $("input[name='" + input_name + "']").val('');
                        },
                        error: function() {
                            msg_error();
                        }
                    });
                }
            }
        });
    }

    /** ajax */
    function ajax() {

    }

    /** 提交get请求 */
    function ajax_get(url) {
        loading();
        $.ajax({
            url: url,
            type: "GET",
            success: function(result) {
                msg_thinkphp(result);
            },
            error: function() {
                msg_error();
            }
        });
    }

    /** 提交delete请求 */
    function ajax_del(url, data) {
        loading();
        $.ajax({
            url: url,
            type: "DELETE",
            data: data,
            success: function(result) {
                msg_thinkphp(result);
            },
            error: function() {
                msg_error();
            }
        });
    }

    /** 提交delete请求 */
    function ajax_del_file(url, data) {
        loading();
        $.ajax({
            url: url,
            type: "DELETE",
            data: data,
            success: function(result) {
                loading('hide') //隐藏加载
                //成功
                if (result.code == '1') {
                    msg_success(result.msg);
                }
                // 错误
                if (result.code == '0') {
                    msg_error(result.msg);
                }
            },
            error: function() {
                msg_error();
            }
        });
    }

    /** 提交post请求 */
    function ajax_post(url, data) {
        loading();
        $.post(url, data, function(response) {
            msg_thinkphp(response)
        }).error(function() {
            msg_error()
        });
    }

    /** 提交put请求 */
    function ajax_put(url, data) {
        ajax_post(url, data);
    }

    /** 消息提示 **/
    function msg(msg = '提示', type = 'info', icon = 'info') {
        new $.zui.Messager(msg, {
            type: type,
            icon: icon // 定义消息图标
        }).show();
    }

    function msg_error(msg = '服务器错误!') {
        loading('hide');
        new $.zui.Messager(msg, {
            type: 'danger',
            icon: 'remove-sign' // 定义消息图标
        }).show();
        return false;
    }

    function msg_success(msg = '恭喜成功!') {
        loading('hide');
        new $.zui.Messager(msg, {
            type: 'success',
            icon: 'check-circle'
        }).show();
        return true;
    }

    // 专门处理 thinkphp 返回数据
    // $this->error() 
    // $this->success()
    // data 数据中 'jump'=>'no' 页面禁止跳转。
    function msg_thinkphp(response) {
        loading('hide') //隐藏加载
        //成功
        if (response.code == '1') {
            msg_success(response.msg);
        }
        // 错误
        if (response.code == '0') {
            msg_error(response.msg);
        }

        // 禁止跳转
        data = response.data;
        if (data && data['jump'] == 'no') {
            return true;
        }

        // 跳转
        if (response.url != '') {
            url = response.url;
            time = Number(response.wait);
            delay_url(url, 1000 * time);
        }

        return false;
    }

    // 定时跳转
    function delay_url(url, time) {
        setTimeout("top.location.href='" + url + "'", time);
    }

    // 文件上传
    function upload(settings = {}, successFunc, startFunc, progressFunc, errorFunc) {
        var defaults = {
            uploadUrl: '/uploads.html',
            inputId: 'sampleupload',
            inputName: 'sampleupload',
            accept: 'image/*', // 限制允许的文件类型 input
            multiple: false, // 允许多选
            data: {}, // 附带数据
            name: 'file', // 上传文件名

            limit: 0, // 允许上传文件数量 0 不限制
            allowedExts: ["jpg", "jpeg", "png", "gif"], // 允许上传后缀
            allowedTypes: ["image/pjpeg", "image/jpeg", "image/png", "image/x-png", "image/gif", "image/x-gif"], // 允许上传类型
            maxFileSize: 10 * 1024 * 1024, //1MB in bytes
        };
        // 合并参数
        $.extend(defaults, settings);
        //console.log(defaults);
        // 生成模块
        var inputFileId = defaults['inputId'];
        var inputFileName = defaults['inputName'];

        var inputFileObj = $("#" + inputFileId);

        // 生成 上传文件控件 并且添加到body 
        if (!inputFileObj[0]) {
            var Ele = $('<input type="file">');
            Ele.attr('id', inputFileId);
            Ele.attr('name', inputFileName);
            Ele.css('display', 'none');
            $('body').append(Ele);
        }

        // 设置 input file 属性
        inputFileObj = $("#" + inputFileId);
        inputFileObj.attr('accept', defaults['accept']);
        if (defaults['multiple']) {
            inputFileObj.attr('multiple', 'multiple');
        } else {
            inputFileObj.removeAttr('multiple');
        }
        // 模拟点击file控件
        inputFileObj.trigger('click');
        // 取消事件绑定
        inputFileObj.off('change');
        // 重新绑定事件 one 只执行一次
        inputFileObj.one('change', function(event) {
            //console.log(event)
            var options = {
                // 上传文件名
                name: defaults['name'],
                // 附带数据
                data: defaults['data'],
                // 限制上传数量
                limit: defaults['limit'],
                // 允许文件后缀
                allowedExts: defaults['allowedExts'],
                // 允许文件类型
                allowedTypes: defaults['allowedTypes'],
                // 允许文件大小
                maxFileSize: defaults['maxFileSize'],
                // 开始上传
                start: startFunc || function(file) {
                    console.log("upload started");
                },
                // 上传过程
                progress: progressFunc || function(progress) {
                    console.log("upload progress: " + Math.round(progress) + "%");
                },
                // 上传完成
                success: successFunc || function(data) {
                    console.log("upload successful!");
                    console.log(data);
                },
                // 上传出错
                error: errorFunc || function(error) {
                    msg_error(error.name + ": " + error.message);
                    console.log(defaults);
                    console.log("upload error: " + error.name + ": " + error.message);
                }
            };
            // simpleUpload 上传插件
            // http://simpleupload.michaelcbrook.com/
            $(this).simpleUpload(defaults['uploadUrl'], options);
        });
    };

    // 
    return {
        loading: loading,
        upload: upload,
        ajax: ajax,
        ajax_get: ajax_get,
        ajax_del: ajax_del,
        ajax_post: ajax_post,
        ajax_put: ajax_put,
        msg: msg,
        msg_error: msg_error,
        msg_success: msg_success,
        msg_thinkphp: msg_thinkphp,
        stop_event: stop_event,
        upload_list_delete: upload_list_delete,
        upload_delete: upload_delete,
    }
}();

//sxj.loading();
/**
 * [description]
 */
$(document).ready(function() {
    // 设置图片背景
    $("[data-imgsrc]").each(function(){
        var imgsrc = $(this).data('imgsrc');
        $(this).css('background-image', 'url(' + imgsrc + ')')
    });

    /** table表格 **/
    if ($("table.datatable")[0]) {
        $('table.datatable').datatable();
    }

    /** 无限级表格树插件 **/
    if ($("table.treetable")[0]) {
        var obj = $("table.treetable");
        obj.treetable({
            initialState: 'expanded',
            indent: 20,
            column: 2,
            expandable: true,
            clickableNodeNames: true,
            stringExpand: "展开", //国际化
            stringCollapse: "收起", //国际化
        });
        // 
        $(".btn-treetable").click(function(event) {
            var btn = $(".btn-treetable"),
                action = btn.data('action');
                obj.treetable(action);
            if (action == 'expandAll') {
                btn.data('action', 'collapseAll').text('全部折叠');
            } else {
                btn.data('action', 'expandAll').text('全部展开');
            }
        });
    }

    /** 图标选择插件 **/
    if ($('select.chosen-icons')[0]) {
        $('select.chosen-icons').chosenIcons();
    }

    /** 无级级分类排序插件 **/
    if ($('#nestable')[0]) {
        $('#nestable').nestable({
            group: 1
        }).on('change', function(e) {
            var list = e.length ? e : $(e.target);
            var output = JSON.stringify(list.nestable('serialize'));
            $('#nestable-output').val(output);
        });
        $('.btn-nestable').on('click', function(e) {
            var btn = $(".btn-nestable"),
                action = btn.data('action');
            $('.dd').nestable(action);
            if (action == 'expandAll') {
                btn.data('action', 'collapseAll').text('全部折叠');
            } else {
                btn.data('action', 'expandAll').text('全部展开');
            }
        });
    }

    /** 复制 **/
    $(".copy").click(function(event) {
        var url = $(this).data('url');
        sxj.ajax_get(url);
    });

    /** 删除 **/
    $('.delete').click(function(event) {
        var url = $(this).data('url');
        bootbox.confirm({
            message: "确定要删除该内容？",
            callback: function(result) {
                if (result) {
                    sxj.ajax_del(url);
                }
            }
        });
    });

    /** 批量删除 **/
    $('.check-delete').click(function(event) {
        var url = $(this).data('url');
        // 获取数据表格实例对象
        var myDatatable = $('table.datatable').data('zui.datatable');
        // 获取行选中数据
        var checksStatus = myDatatable.checks;
        if (checksStatus == undefined) {
            return sxj.msg_error('请先选择内容！');
        }
        url = url + '?id=' + checksStatus.checks.toString();
        bootbox.confirm({
            message: "确定要删除选中的内容？",
            callback: function(result) {
                if (result) {
                    sxj.ajax_del(url);
                }
            }
        });
    });

    if ($('form#form-page-submit')[0]) {
        /** ajax提交表单 页面级 **/
        $('form#form-page-submit').validator().on('submit', function(e) {
            if (e.isDefaultPrevented()) {
                return false;
            }

            // 编辑器
            if (typeof tinyMCE == 'object') {
                tinyMCE.triggerSave();
            }

            // 使用jquery.form.js插件提交
            $('#form-page-submit').ajaxSubmit({
                beforeSubmit: sxj.loading,
                success: sxj.msg_thinkphp
            });

            return false;
        })
    }

    if ($('form#form-modal-submit')[0]) {
        /** ajax提交表单 弹出框 **/
        $('form#form-modal-submit').validator().on('submit', function(e) {
            if (e.isDefaultPrevented()) {
                return false;
            }

            var myfrom = $(e.target);
            if (myfrom.attr('action') == '' || myfrom.attr('action') == undefined) {
                sxj.msg_error('未配置表单的 action ');
                return false;
            }

            // 使用jquery.form.js插件提交
            $(this).ajaxSubmit({
                beforeSubmit: sxj.loading,
                success: sxj.msg_thinkphp
            });
            return false;
        })
    }

    /** 当show方法被调用时，此事件将被立即触发。 * */
    $("#modal-create").on('shown.zui.modal', function(event) {
        var myform = $("#form-modal-submit");
        myform.resetForm(); // 表单重置

        var el = $(event.relatedTarget),
            id = el.attr('data-id'),
            url = el.attr('data-url'),
            action = el.attr('data-action');

        if (action != '') {
            myform.attr('action', action);
        }

        // 获取数据 自动填充到表单
        if (url != undefined && url != '') {
            sxj.loading();
            $.getJSON(url, function(json, textStatus) {
                sxj.loading('hide');
                // 使用jquery.autofill.js插件赋值
                myform.autofill(json['data']);
            }).error(function() {
                sxj.msg_error()
            });
        }
    });

    /** 更新排序
     * <input type="number" class="input-sm sort" data-url="/site/sort" data-old-sort="1" data-id="1" value="1">
     */
    $("input.sort").on('change', function(e) {
        sxj.stop_event(e);
        var url = $(this).data('url'),
            id = $(this).data('id'),
            oldSort = $(this).data('old-sort'),
            sort = $(this).val();
        if (oldSort == sort) {
            return false;
        }
        sxj.ajax_post(url, { id: id, sort: sort });
    });


    $("#cache_clear").click(function(event) {
        var url = $(this).attr('href');
        sxj.ajax_get(url);
        return false;
    });

});